import { getSectInfo, getSectList } from '@/api/sect'

const state = {
  // 当前用户的门派信息
  sectInfo: null,
  // 门派列表
  sectList: [],
  // 加载状态
  loading: false,
  // 最后更新时间
  lastUpdated: null
}

const mutations = {
  SET_SECT_INFO(state, sectInfo) {
    state.sectInfo = sectInfo
    state.lastUpdated = Date.now()
  },
  
  SET_SECT_LIST(state, sectList) {
    state.sectList = sectList
  },
  
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  
  CLEAR_SECT_INFO(state) {
    state.sectInfo = null
    state.lastUpdated = null
  }
}

const actions = {
  // 获取门派信息
  async fetchSectInfo({ commit, state }) {
    // 如果数据是最近5分钟内获取的，直接返回缓存数据
    if (state.sectInfo && state.lastUpdated && (Date.now() - state.lastUpdated < 5 * 60 * 1000)) {
      return state.sectInfo
    }
    
    try {
      commit('SET_LOADING', true)
      const response = await getSectInfo()
      
      if (response.code === 1) {
        // 映射后端字段名到前端期望的字段名
        const sectInfo = {
          ...response.data,
          sectId: response.data.id, // 将后端的id映射为sectId
          sectName: response.data.name // 将后端的name映射为sectName
        }
        commit('SET_SECT_INFO', sectInfo)
        return sectInfo
      } else {
        // 如果是未加入门派的错误，设置sectInfo为特殊标记
        if (response.msg && response.msg.includes('未加入任何门派')) {
          commit('SET_SECT_INFO', { notJoined: true })
          return { notJoined: true }
        }
        throw new Error(response.msg || '获取门派信息失败')
      }
    } catch (error) {
      console.error('获取门派信息失败:', error)
      // 如果是网络错误或其他错误，也检查错误信息
      if (error.message && error.message.includes('未加入任何门派')) {
        commit('SET_SECT_INFO', { notJoined: true })
        return { notJoined: true }
      }
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 获取门派列表
  async fetchSectList({ commit }) {
    try {
      commit('SET_LOADING', true)
      const response = await getSectList()
      
      if (response.code === 1) {
        const sectList = (response.data || []).map(sect => ({
          ...sect,
          canJoin: !sect.isJoined && (sect.memberCount || 0) < (sect.maxMembers || 100),
          memberCount: sect.memberCount || 0,
          maxMembers: sect.maxMembers || 100
        }))
        commit('SET_SECT_LIST', sectList)
        return sectList
      } else {
        throw new Error(response.msg || '获取门派列表失败')
      }
    } catch (error) {
      console.error('获取门派列表失败:', error)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 更新门派信息（用于加入门派后的状态更新）
  updateSectInfo({ commit }, sectInfo) {
    commit('SET_SECT_INFO', sectInfo)
  },
  
  // 清除门派信息（用于退出门派）
  clearSectInfo({ commit }) {
    commit('CLEAR_SECT_INFO')
  }
}

const getters = {
  // 是否已加入门派
  hasJoinedSect: state => {
    return state.sectInfo && (state.sectInfo.sectId || state.sectInfo.id)
  },
  
  // 获取门派ID
  sectId: state => {
    return state.sectInfo ? (state.sectInfo.sectId || state.sectInfo.id) : null
  },
  
  // 获取门派名称
  sectName: state => {
    return state.sectInfo ? (state.sectInfo.sectName || state.sectInfo.name) : ''
  },
  
  // 是否正在加载
  isLoading: state => state.loading
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}